package completablefuture;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutionException;
import java.util.function.Function;
import java.util.function.Supplier;

/**
 * @description: 嵌套 CompletableFuture
 * @author: WangPengPeng
 * @create: 2021-11-22 21:43
 **/
public class Demo6ThenCompose {

    // 嵌套的CompletableFuture
 /*   public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<CompletableFuture<Integer>> future = CompletableFuture.supplyAsync(() -> {
            return "hello world";
        }).thenApply(new Function<String, CompletableFuture<Integer>>() {
            @Override
            public CompletableFuture<Integer> apply(String s) {
                CompletableFuture<Integer> innerFuture = CompletableFuture.supplyAsync(() -> {
                    return s.length();
                });
                return innerFuture;
            }
        });

        CompletableFuture<Integer> future1 = future.get();
        System.out.println(future1.get());
    }*/

    // 非嵌套的CompletableFuture
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        CompletableFuture<Integer> future =
                CompletableFuture.supplyAsync(new Supplier<String>() {

            @Override
            public String get() {
                return "hello world";
            }
        }).thenCompose(new Function<String, CompletionStage<Integer>>() {
            @Override
            public CompletionStage<Integer> apply(String s) {
               return CompletableFuture.supplyAsync(new Supplier<Integer>() {
                    @Override
                    public Integer get() {
                        return s.length();
                    }
                });

            }
        });

        Integer future1 = future.get();
        System.out.println(future1);
    }
}
